package com.sso.oauth2.server.config.auath2.impl;

import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

/**
 * 自定义用户实现 Service
 *
 * @author yins
 * @date 2021/07/12 16:44
 **/
@Service
public class CustomUserDetailsImpl implements UserDetailsService {

    private static final PasswordEncoder PASSWORD_ENCODER = new BCryptPasswordEncoder();

    private static final Map<String, String> userMap = new HashMap<>();

    static {
        userMap.put("yins", PASSWORD_ENCODER.encode("test"));
        userMap.put("duia", PASSWORD_ENCODER.encode("test"));
        userMap.put("duia1", PASSWORD_ENCODER.encode("test"));
        userMap.put("duia2", PASSWORD_ENCODER.encode("test"));
    }


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        String pwd = userMap.get(username);
        Collection<SimpleGrantedAuthority> authorities = new ArrayList<>();
        authorities.add(new SimpleGrantedAuthority("role"));
        authorities.add(new SimpleGrantedAuthority("ROLE_admin1"));
        User user = new User(username, pwd, authorities);
        return user;
    }
}
